import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import {
  NavBar,
  Icon,
  List,
  Switch,
  InputItem,
  Picker,
  Toast,
  Modal,
} from "antd-mobile";
import arrArea from "../../area/area";
import {
  sendAddress,
  getAddressDetail,
  deleteAddress,
  changeDefaultAddress,
} from "../../data/apiLiao";
import styles from "./EditAddress.module.scss";
class EditAddress extends Component {
  state = {
    form: {
      addressDetail: "",
      areaCode: "",
      province: "",
      city: "",
      district: "",
      isDefault: false,
      name: "",
      tel: "",
      postCode: "",
    },
    addrTxt: "",
    id: "",
  };
  componentDidMount() {
    this.getSingleAddress();
  }
  // 获取地址信息
  getSingleAddress = async () => {
    let search = this.props.location.search;
    if (search) {
      let id = parseInt(search.split("=")[1]);
      this.setState({
        id: id,
      });
      let res = await getAddressDetail(id);
      if (res.success) {
        res.data &&
          this.setState((preState) => {
            preState.form.addressDetail = res.data.addressDetail;
            preState.form.areaCode = res.data.areaCode;
            preState.form.province = res.data.province;
            preState.form.city = res.data.city;
            preState.form.district = res.data.district;
            preState.form.isDefault = res.data.isDefault;
            preState.form.name = res.data.name;
            preState.form.tel = res.data.tel;
            preState.form.postCode = res.data.postCode;
            preState.form.id = res.data.id;
            return {
              form: preState.form,
            };
          });
        if (res.data) {
          if (res.data.areaCode === "900000") {
            // 海外
            this.setState({
              addrTxt: res.data.city,
            });
          } else if (res.data.province === res.data.city) {
            //如果省市同名，保留一个
            this.setState({
              addrTxt: res.data.city + "/" + res.data.district,
            });
          } else {
            this.setState({
              addrTxt:
                res.data.province +
                "/" +
                res.data.city +
                "/" +
                res.data.district,
            });
          }
        }
      }
    }
  };
  // 姓名
  handlerName = (el) => {
    this.setState((preState) => {
      preState.form.name = el;
      return {
        form: preState.form,
      };
    });
  };
  // 电话
  handlerTel = (el) => {
    this.setState((preState) => {
      preState.form.tel = el;
      return {
        form: preState.form,
      };
    });
  };
  // 地址详情
  handlerDetail = (el) => {
    this.setState((preState) => {
      preState.form.addressDetail = el;
      return {
        form: preState.form,
      };
    });
  };

  // 选择地区
  selectAddress = (e) => {
    // 将区代码赋给areaCode
    this.setState((preState) => {
      preState.form.areaCode = e[e.length - 1];
      return {
        form: preState.form,
      };
    });
    let province = "";
    let city = "";
    let district = "";
    arrArea.forEach((v) => {
      // 判断地区是否为海外
      if (e[0] === "900000") {
        v.children.forEach((k) => {
          if (k === e[1]) {
            city = k.label;
          }
        });
      } else {
        if (v.value === e[0]) {
          province = v.label;
          this.setState((preState) => {
            preState.form.province = v.label;
            return {
              form: preState.form,
            };
          });
        }
        v.children.forEach((k) => {
          if (k.value === e[1]) {
            city = k.label;
            this.setState((preState) => {
              preState.form.city = k.label;
              return {
                form: preState.form,
              };
            });
          }
          k.children.forEach((j) => {
            if (j.value === e[2]) {
              district = j.label;
              this.setState((preState) => {
                preState.form.district = j.label;
                return {
                  form: preState.form,
                };
              });
            }
          });
        });
      }
    });

    if (e[0] === "900000") {
      // 海外
      this.setState({
        addrTxt: city,
      });
    } else if (province === city) {
      //如果省市同名，保留一个
      this.setState({
        addrTxt: city + "/" + district,
      });
    } else {
      this.setState({
        addrTxt: province + "/" + city + "/" + district,
      });
    }
  };
  // 滑动开关
  handlerSwitch = () => {
    this.setState(
      (preState) => {
        preState.form.isDefault = !preState.form.isDefault;
        return {
          form: preState.form,
        };
      },
      async () => {
        let id = this.state.id;
        if (id) {
          let status = this.state.form.isDefault;
          let res = await changeDefaultAddress({ id, status });
          if (res.success) {
            // 重新获取地址信息
            this.getSingleAddress();
          }
        }
      }
    );
  };

  // 点击保存按钮
  handlerSave = async () => {
    let flag = true;
    if (this.state.form.name === "") {
      flag = false;
      Toast.info("请填写姓名！", 1);
    } else if (this.state.form.tel === "") {
      flag = false;
      Toast.info("请填写手机号", 1);
    } else if (this.state.form.areaCode === "") {
      flag = false;
      Toast.info("请选择地区", 1);
    } else if (this.state.form.addressDetail === "") {
      flag = false;
      Toast.info("请填写详细地址", 1);
    }
    // 用验证手机号
    if (this.state.form.tel.length !== 11 || this.state.form.tel[0] !== "1") {
      Toast.info("手机号有误，请重新输入！", 1);
      flag = false;
    }
    if (flag) {
      let res = await sendAddress(this.state.form);
      if (res.success) {
        this.props.history.replace("address");
      }
    }
  };
  // 删除该地址
  handlerDelete = async (id) => {
    let res = await deleteAddress(id);
    if (res.success) {
      this.props.history.replace("address");
    }
  };

  render() {
    return (
      <div className="editAddress">
        <div className={styles.editAddressHead}>
          <NavBar
            mode="light"
            icon={[
              <Icon type="left" key="btn" />,
              <div className={styles.return} key="txt">
                返回
              </div>,
            ]}
            onLeftClick={() => this.props.history.replace("address")}
          >
            编辑收货地址
          </NavBar>
        </div>
        <div className={styles.formWarp}>
          <div className={styles.editForm}>
            <div className={styles.name}>
              <InputItem
                clear
                placeholder="收货人姓名"
                value={this.state.form.name}
                onChange={(el) => {
                  this.handlerName(el);
                }}
              >
                姓名
              </InputItem>
            </div>
            <div className={styles.phone}>
              <InputItem
                clear
                placeholder="收货人手机号"
                type="number"
                value={this.state.form.tel}
                onChange={(el) => {
                  this.handlerTel(el);
                }}
              >
                电话
              </InputItem>
            </div>
            <div className={styles.address}>
              <Picker
                extra={
                  this.state.form.areaCode ? this.state.addrTxt : "选择省/市/区"
                }
                data={arrArea}
                onOk={(e) => this.selectAddress(e)}
                onDismiss={() => Toast.info("已取消", 1)}
              >
                <List.Item arrow="horizontal">地区</List.Item>
              </Picker>
            </div>
            <div className={styles.addressDetail}>
              <InputItem
                clear
                placeholder="街道门牌、楼层房间号等信息"
                value={this.state.form.addressDetail}
                onChange={(el) => {
                  this.handlerDetail(el);
                }}
              >
                详细地址
              </InputItem>
            </div>
          </div>
        </div>
        <div className={styles.setDefault}>
          <List.Item
            extra={
              <Switch
                checked={this.state.form.isDefault}
                onChange={this.handlerSwitch}
              />
            }
          >
            设为默认收货地址
          </List.Item>
        </div>
        <div className={styles.saveEdit}>
          <div className={styles.saveBtn} onClick={this.handlerSave}>
            保存
          </div>
          {this.state.id ? (
            <div
              className={styles.deleteBtn}
              onClick={() =>
                Modal.alert("确定要删除吗", "", [
                  { text: "取消", onPress: () => {} },
                  {
                    text: "确认",
                    onPress: () => {
                      this.handlerDelete(this.state.id);
                    },
                  },
                ])
              }
            >
              删除
            </div>
          ) : (
            ""
          )}
        </div>
      </div>
    );
  }
}

export default withRouter(EditAddress);
